package com.xiaomi.dao.impl;

import com.xiaomi.dao.ProductDao;
import com.xiaomi.entity.Product;
import com.xiaomi.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.util.List;

/**
 * TODO
 *
 * @author jy
 * @date 2021/5/24
 */
public class ProductDaoImpl implements ProductDao {

    private final QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());

    @Override
    public List<Product> list(int tid, int begin, int pageNum) throws Exception {
        String sql = "select * from product where tid=? limit ?,?";
        return queryRunner.query(sql, new BeanListHandler<>(Product.class),
                tid, begin, pageNum);
    }

    @Override
    public int count(int tid) throws Exception {
        String sql = "select count(*) from product where tid=?";
        Object count = queryRunner.query(sql, new ScalarHandler(),tid);
        return Integer.parseInt("" + count);
    }

    @Override
    public Product getProductByPid(int pid) throws Exception {
        String sql = "select * from product where pid=?";
        return queryRunner.query(sql, new BeanHandler<>(Product.class),pid);
    }
}
